<template>
  <HeaderComponent
    :loading="loading"
    ref="headerRef"
    @question-type-change="change"
  />
  <ContentComponent :loading="loading" ref="contentRef" />
  <SourceComponent :loading="loading" ref="sourceRef" />
</template>

<script lang="ts">
import { ref, Ref, computed } from "vue";
import HeaderComponent from "./header.vue";
import ContentComponent from "./content.vue";
import SourceComponent from "./source.vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import $ from "$";

export default {
  components: { HeaderComponent, ContentComponent, SourceComponent },
  props: ["id", "subjectId"],
  setup(props) {
    let store = useStore();
    let headerRef: Ref<any> = ref(null);
    let contentRef: Ref<any> = ref(null);
    let sourceRef: Ref<any> = ref(null);

    /* ------------- 保存 ------------- */
    let subjectId = props.subjectId ? props.subjectId : computed(() => store.getters.subject.code).value;
    const save = async (resolve, reject) => {
      let contentGroup = contentRef.value.validator();
      let headerGroup = $.clone(headerRef.value.formGroup);
      headerGroup.chapterKnowles = headerGroup.chaptersIds.map(chapterId => ({ chapterId }));
      let sourceGroup = $.clone(sourceRef.value.questionSources);
      if (contentGroup) {
        sourceGroup && sourceGroup.map((s) => {
          if (s.provinceCity) {
            let [provinceId, cityId, areaId] = s.provinceCity;
            s.provinceId = provinceId;
            s.cityId = cityId;
            s.areaId = areaId;
          }
          delete s.schoolList;
          delete s.provinceCity;
          return s;
        });
        contentGroup.basicQuestionType = contentGroup.baseType;
        let params = {
          ...questionInfo,
          ...contentGroup,
          ...headerGroup,
          subjectId,
          id: props.id,
          questionSources: sourceGroup,
          operationType: 1,
        };
        let url = `/tiku/question/${props.id ? "editQuestion" : "add"}`;
        let res = await $.http.json(url, params);
        ElMessage[res.result ? "success" : "warning"](
          res.msg || `${props.id ? "编辑" : "添加"}试题成功`
        );
        resolve(res);
      } else {
        reject();
      }
    };

    /* ------------- 题型更改 ------------- */
    const change = (e) => contentRef.value.questionTypeChange(e);

    /* ------------- 编辑回显 ------------- */
    let loading = ref(false);
    if (props.id) {
      loading.value = true;
      $.http.post("/tiku/question/getQuestion", { id: props.id }).then((res) => __init(res.json));
    }
    let questionInfo: any = null;
    const __init = (info) => {
      loading.value = false;
      questionInfo = info;
      __headerHandle(info);
      __contentHandle(info)
      info.rightAnswer.forEach(i => i.content = i.content.replace(/【答案】/, ''))
      if (info.basicQuestionType < 3) {
        setTimeout(() => {
          let init = Array.from(new Array(4), (i, idx) => ({ no: idx + 1, content: null, checked: false }));
          let value = !info.option ? init : info.rightAnswer ? info.option.map(i => {i.checked = !!info.rightAnswer.find(a => a.no === i.no); return i}) : info.option;
          contentRef.value.typeRef.options = value;
        });
      } else if (info.basicQuestionType === 3) {
        setTimeout(() => {
          contentRef.value.typeRef.options = info.rightAnswer;
        });
      } else if (info.basicQuestionType === 7) {
        setTimeout(() => {
          contentRef.value.typeRef.option = info.option;
        });
      } else if (info.basicQuestionType === 9) {

      } else {
        setTimeout(() => {
          info.rightAnswer && (contentRef.value.typeRef.answer = info.rightAnswer[0].content);
        });
      }

      setTimeout(() => {
        sourceRef.value.questionSources = info.questionSources || [];
      });
    };

    const __headerHandle = ({ knowledgePoints, type, difficult, year, source, category, questionSources, gradeId, chapterKnowles }) => {
      questionSources && questionSources.map((s) => {
        let provinceCity: string[] = [];
        s.cityId && (provinceCity = [s.provinceId, s.cityId]);
        s.areaId && provinceCity.push(s.areaId);
        s.provinceCity = provinceCity;
        s.areaId && sourceRef.value.getSchoolList(s.provinceCity, s);
        return s;
      });
      headerRef.value.formGroup.knowledgePoints = knowledgePoints || [];
      headerRef.value.formGroup.chaptersIds = chapterKnowles.map((ele) => ele.chapterId) || [];
      headerRef.value.formGroup.type = type;
      headerRef.value.formGroup.difficult = difficult;
      headerRef.value.formGroup.year = year;
      headerRef.value.formGroup.source = source;
      headerRef.value.formGroup.category = category;
      headerRef.value.formGroup.gradeId = gradeId;
    }

    const __contentHandle = ({ title, analysis, basicQuestionType, childs, option, voicePath, videoPath, silentVideoPath }) => {
      if (childs && childs.length) {
        contentRef.value.formGroup.title = `${title}<br>${
          childs.map((i, idx) => `${idx + 1}.${i.title}<br>${ i.option ? i.option.map((c) => `${c.name}.${c.content}`).join("<br>") : [] }`).join("<br>")
        }`;
      } else if (basicQuestionType === 10) {
        contentRef.value.formGroup.title = `${title}<br>${
          option.map( (i) => `${i.name}.<br>${i.childs.map((c) => `${c.name}.${c.content}`).join("<br>")}`).join("<br>")
        }`;
      } else {
        contentRef.value.formGroup.title = title;
      }
      contentRef.value.formGroup.analysis = analysis;
      contentRef.value.formGroup.voicePath = voicePath;
      contentRef.value.formGroup.videoPath = videoPath;
      contentRef.value.formGroup.silentVideoPath = silentVideoPath;
      contentRef.value.baseType = basicQuestionType;
    }

    return { headerRef, contentRef, sourceRef, save, change, loading };
  },
};

</script>

<style lang="scss" scoped>
</style>
